package fhp.hlhj.giantfold.utils

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.Log
import java.io.*

/**
 * author: FHP
 * data: on 2018\1\11 0011 15:27
 * E-Mail: 103945089@qq.com
 */
object SPUtils {
    private val loginType="login"
    private val FILENAME = "userinfo_save"
    private val TAG="info"
    private val KEY2 = "userinfo"
    private val TBLoginKey="taobao"
    private val IsFirst="isFirst"
    /**
     * 存openId
     */
    private val user="user"
    private val OPENID="openId"
    /**
     * 存弹框时间
     */
    private val TIME1="time1"
    private val TIME2="time2"
    private val TIME3="time3"
    /**
     * Jd
     */
    private val JD="JD"


    /**
     * 判断是否第一次进入app
     */

    fun saveIsFirst(context: Context,type: Int){
        val sp = context.getSharedPreferences(IsFirst, Context.MODE_PRIVATE)
        sp.edit().putInt("isFirst",type).apply()
    }
    /**
     * 读取是否第一次登陆
     */
    fun getIsFirst(context: Context): Int {
        val sp = context.getSharedPreferences(IsFirst, Context.MODE_PRIVATE)
        return sp.getInt("isFirst",1)
    }
    /**
     * 存淘宝登录状态
     */
    fun saveTaoBaoLogin(context: Context,type: Int){
        val sp = context.getSharedPreferences(TBLoginKey, Context.MODE_PRIVATE)
        sp.edit().putInt("isLogin",type).apply()
    }
    /**
     * 读淘宝登录状态
     */
    fun getTaoBaoLogin(context: Context): Int {
        val sp = context.getSharedPreferences(TBLoginKey, Context.MODE_PRIVATE)
        return sp.getInt("isLogin",0)
    }
    /**
     * 存JDToken
     */

    fun saveJDToken(context: Context,token:String){
        val sp = context.getSharedPreferences(JD, Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putString("token",token)
        edit.apply()
    }
    /***
     * 取JDTOken
     */
    fun getJDToken(context: Context): String? {
        val sp = context.getSharedPreferences(JD, Context.MODE_PRIVATE)
        return sp.getString("token","");
    }

    /**
     * 存openid
     */
    fun saveOpenId(context: Context,openid:String?){
        val sp = context.getSharedPreferences(OPENID, Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putString(OPENID,openid)
        edit.apply()
    }

    fun readOpenId(context: Context): String? {
        val sp = context.getSharedPreferences(OPENID, Context.MODE_PRIVATE)
        return sp.getString(OPENID,null)
    }
    /**
     * -1-未登录
     * 0-手机登录
     * 1-微信登录
     * 2-QQ登录
     */
    fun saveLoginType(context: Context,type:Int){
        val sp = context.getSharedPreferences(loginType, Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putInt("loginType",type)
        edit.apply()
    }

    fun readLoginType(context: Context): Int {
        val sp = context.getSharedPreferences(loginType, Context.MODE_PRIVATE)
        return sp.getInt("loginType",-1)
    }


    fun saveUserIsLogin(context: Context,isLogin: Boolean){
        val sp = context.getSharedPreferences(loginType, Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putBoolean("islogin",isLogin)
        edit.apply()
    }
    fun readUserIsLogin(context: Context): Boolean {
        val sp = context.getSharedPreferences(loginType, Context.MODE_PRIVATE)
        return sp.getBoolean("islogin",false)
    }
    fun saveUser(context: Context,userName:String,pwd:String){
        val sp = context.getSharedPreferences(user, Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putString("userName",userName)
        edit.putString("userPwd",pwd)
        edit.apply()
    }

    fun saveUser(context: Context, obj: Any) {
        try {
            Log.e(TAG, "saveObject: 开始")

            // 保存对象
            val sharedata = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE).edit()
            //先将序列化结果写到byte缓存中，其实就分配一个内存空间
            val bos = ByteArrayOutputStream()
            val os = ObjectOutputStream(bos)
            //将对象序列化写入byte缓存
            Log.e(TAG, "saveObject: 写入")
            os.writeObject(obj)
            Log.e(TAG, "saveObject: 关流")
            os.close()
            bos.close()
            Log.e(TAG, "saveObject: 关流完成")
            //将序列化的数据转为16进制保存
            val bytesToHexString = bytesToHexString(bos.toByteArray())
            //保存该16进制数组
            sharedata.putString(KEY2, bytesToHexString)
            sharedata.commit()
            Log.e(TAG, "saveObject: 成功")
        } catch (e: IOException) {
            e.printStackTrace()
            Log.e("", "保存obj失败")
        }

    }

    /**
     * desc:将数组转为16进制
     * @param bArray
     * @return
     * modified:
     */
    fun bytesToHexString(bArray: ByteArray?): String? {
        if (bArray == null) {
            return null
        }
        if (bArray.size == 0) {
            return ""
        }
        val sb = StringBuffer(bArray.size)
        var sTemp: String
        for (i in bArray.indices) {
            sTemp = Integer.toHexString(0xFF and bArray[i].toInt())
            if (sTemp.length < 2)
                sb.append(0)
            sb.append(sTemp.toUpperCase())
        }
        return sb.toString()
    }

    fun readUserInfo(context: Context): Any? {
        try {
            val sharedata = context.getSharedPreferences(FILENAME, 0)
            if (sharedata.contains(KEY2)) {
                val string = sharedata.getString(KEY2, "")
                if (TextUtils.isEmpty(string)) {
                    return null
                } else {
                    //将16进制的数据转为数组，准备反序列化
                    val stringToBytes = StringToBytes(string)
                    val bis = ByteArrayInputStream(stringToBytes)
                    val `is` = ObjectInputStream(bis)
                    //返回反序列化得到的对象
                    return `is`.readObject()
                }
            }
        } catch (e: StreamCorruptedException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        } catch (e: IOException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        } catch (e: ClassNotFoundException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }

        //所有异常返回null
        return null

    }

    /**
     * desc:将16进制的数据转为数组
     *
     * 创建人：聂旭阳 , 2014-5-25 上午11:08:33
     * @param data
     * @return
     * modified:
     */
    fun StringToBytes(data: String): ByteArray? {
        val hexString = data.toUpperCase().trim { it <= ' ' }
        if (hexString.length % 2 != 0) {
            return null
        }
        val retData = ByteArray(hexString.length / 2)
        var i = 0
        while (i < hexString.length) {
            val int_ch: Int  // 两位16进制数转化后的10进制数
            val hex_char1 = hexString[i] ////两位16进制数中的第一位(高位*16)
            val int_ch3: Int
            if (hex_char1 >= '0' && hex_char1 <= '9')
                int_ch3 = (hex_char1.toInt() - 48) * 16   //// 0 的Ascll - 48
            else if (hex_char1 >= 'A' && hex_char1 <= 'F')
                int_ch3 = (hex_char1.toInt() - 55) * 16 //// A 的Ascll - 65
            else
                return null
            i++
            val hex_char2 = hexString[i] ///两位16进制数中的第二位(低位)
            val int_ch4: Int
            if (hex_char2 >= '0' && hex_char2 <= '9')
                int_ch4 = hex_char2.toInt() - 48 //// 0 的Ascll - 48
            else if (hex_char2 >= 'A' && hex_char2 <= 'F')
                int_ch4 = hex_char2.toInt() - 55 //// A 的Ascll - 65
            else
                return null
            int_ch = int_ch3 + int_ch4
            retData[i / 2] = int_ch.toByte()//将转化后的数放入Byte里
            i++
        }
        return retData
    }

    fun readUserName(context: Context): String {
        val sp = context.getSharedPreferences(user, Context.MODE_PRIVATE)
        return sp.getString("userName","")
    }
    fun readUserPwd(context: Context): String {
        val sp = context.getSharedPreferences(user, Context.MODE_PRIVATE)
        return sp.getString("userPwd","")
    }

    @SuppressLint("CommitPrefEdits")
            /***
     * 保存时间戳
     */
    fun saveTime(context: Context,type:Int,time:String){
        when(type){
            1->{
                val sp = context.getSharedPreferences(TIME1, Context.MODE_PRIVATE)
                val edit = sp.edit()
                edit.putString("time",time)
                edit.apply()
            }
            2->{
                val sp = context.getSharedPreferences(TIME2, Context.MODE_PRIVATE)
                val edit = sp.edit()
                edit.putString("time",time)
                edit.apply()
            }
            3->{
                val sp = context.getSharedPreferences(TIME3, Context.MODE_PRIVATE)
                val edit = sp.edit()
                edit.putString("time",time)
                edit.apply()
            }
        }
    }
    /**
     * 读取时间戳
     */
    fun readTime(context: Context,type: Int): String? {
        when(type){
            1->{
                val sp = context.getSharedPreferences(TIME1, Context.MODE_PRIVATE)
                return sp.getString("time",null)
            }
            2->{
                val sp = context.getSharedPreferences(TIME2, Context.MODE_PRIVATE)
                return sp.getString("time",null)
            }
            3->{
                val sp = context.getSharedPreferences(TIME3, Context.MODE_PRIVATE)
                return sp.getString("time",null)
            }
            else->{
                return null
            }
        }
    }
}